package com.datax.web.webbase;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class IndexController extends AbstractCommonController{

	@RequestMapping("/callserverfunction.spr")
	@ResponseBody
	public Object callServerFunction(HttpServletRequest request){
		String freshStr = request.getParameter("_callFunParams");

	    if ((freshStr == null) || (freshStr.trim().length() == 0))
	      return proccessResult("ERROR", "执行服务端方法必须指定类全名、方法名", freshStr);
	    try
	    {
	      JSONArray arrays = JSONArray.fromObject(freshStr);
	      if (arrays.size() < 2) {
	        return proccessResult("ERROR", "执行服务端方法错误，必须指定类全名、方法名；传入参数[" + freshStr + "]", freshStr);
	      }
	      if (arrays.size() == 2) {
	        Object result = callFunction(arrays.getString(0), arrays.getString(1), new Object[0]);
	        return proccessResult("SUCCESS", "执行服务端方法成功", result);
	      }
	      Object[] args = new Object[arrays.size() - 2];
	      for (int i = 2; i < arrays.size(); i++)
	        if ((!(arrays.get(i) instanceof JSONObject)) || (!((JSONObject)arrays.get(i)).isNullObject()))
	        {
	          args[(i - 2)] = arrays.get(i);
	        }
	      Object result = callFunction(arrays.getString(0), arrays.getString(1), args);
	      return proccessResult("SUCCESS", "执行服务端方法成功", result);
	    }
	    catch (Exception e) {
	      return handlerException(e);
	    }
	}
	
	private Object callFunction(String className, String method, Object[] args)
		    throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException
		  {
		    Class clazz = Class.forName(className);
		    Object bean = FrameWorkApplicationContextAware.getApplicationContext().getBean(clazz);

		    if (bean == null) {
		      if (clazz.isInterface()) {
		        throw new NoSuchMethodException("调用远程服务，指定的接口[" + className + "]不存在任何可供使用的实现类");
		      }
		      bean = clazz.newInstance();
		    }

		    Method[] methods = clazz.getMethods();

		    Method em = null;
		    Type[] types;
		    List list;
		    for (Method m : methods)
		    {
		      if (m.getName().equals(method)) {
		        types = m.getGenericParameterTypes();
		        if ((args == null) || (args.length == 0)) {
		          if (types.length == 0) {
		            em = m;
		            break;
		          }

		        }
		        else if (types.length == args.length) {
		          boolean mf = true;
		          for (int i = 0; i < types.length; i++) {
		            Object o = args[i];
		            if (o != null)
		            {
		              if (!types[i].toString().equals(o.getClass().toString()))
		              {
		                if ((!"int".equals(types[i].toString())) || (!Integer.class.getCanonicalName().equals(o.getClass().getCanonicalName())))
		                {
		                  if ((!"boolean".equals(types[i].toString())) || (!Boolean.class.getCanonicalName().equals(o.getClass().getCanonicalName())))
		                  {
		                    if ((!"char".equals(types[i].toString())) || (!Character.class.getCanonicalName().equals(o.getClass().getCanonicalName())))
		                    {
		                      if ((!"byte".equals(types[i].toString())) || (!Byte.class.getCanonicalName().equals(o.getClass().getCanonicalName())))
		                      {
		                        if ((!"long".equals(types[i].toString())) || (!Long.class.getCanonicalName().equals(o.getClass().getCanonicalName())))
		                        {
		                          if ((!"float".equals(types[i].toString())) || (!Float.class.getCanonicalName().equals(o.getClass().getCanonicalName())))
		                          {
		                            if ((!"short".equals(types[i].toString())) || (!Short.class.getCanonicalName().equals(o.getClass().getCanonicalName())))
		                            {
		                              if ((!"double".equals(types[i].toString())) || (!Double.class.getCanonicalName().equals(o.getClass().getCanonicalName()))){
		                            	  
		                              }
		                            }
		                          }
		                        }
		                      }
		                    }
		                  }
		                }
		              }
		            }
		          }
		          if (mf) { em = m; break;
		          }
		        }

		      }
		    }
		    if (em == null) {
			      list = new ArrayList(args.length);
			      for (Object o : args) {
			        list.add(o);
			      }
			      throw new NoSuchMethodException("调用远程服务，指定的类[" + className + "]不存在待调用的方法[" + method + "]，参数：" + list);
			    }
		    return em.invoke(bean, args);
		  }
}
